﻿using JXC.Core.Models;
using JXC.WebAPI.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
//using JXC.Core;
//using JXC.Utility;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;
using JXC.Utility;
using Microsoft.AspNetCore.Authorization;
using JXC.Core.Repository;
using JXC.Application.Dtos;
using Microsoft.AspNetCore.Http;
//using JXC.Core.Repository;



// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace JXC.WebAPI.Controllers
{
    /// <summary>
    /// 权限管理 控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorityManagementController : BaseController
    {
        private ILogger<AuthorityManagementController> _logger = null;

        public IConfiguration _configuration;
        private readonly IRepository<UserInfos, int> _repository;
        public AuthorityManagementController(ILoggerFactory factory,
            ILogger<AuthorityManagementController> logger,
            IConfiguration configuration
            , IRepository<UserInfos, int> repository)
        {
            _logger = logger;
            _configuration = configuration;

            _repository = repository;
        }
        //[Route("Get")]
        //[Authorize]
        //[Authorize(AuthenticationSchemes = "Bearer")]
        [HttpGet]
        public IActionResult GetTo([FromQuery] string user)
        {
            return Ok(user);
        }
       

        // GET: api/<AuthorityManagement>
        //[Route("Post")]
        [HttpPost]
        public async Task<IActionResult> login([FromHeader] UserInfos userInfos)
        {

            //验证用户名和密码
            var the = await _repository.FirstOrDefaultAsync(x => x.UserName == userInfos.UserName);

            if (the != null)
            {

                var Id = the.Id + "";
                if (userInfos.UserPwd == the.UserPwd)
                {
                    //颁发token
                    //创建jwt
                    //header
                    var singingAlorithm = SecurityAlgorithms.HmacSha256;
                    //payload(添加自定义内容)
                    var claims = new List<Claim> { 
                //sub     JwtRegisteredClaimNames.sub,用户id
                new Claim(JwtRegisteredClaimNames.Sub,Id)
              };
                    //signiture 私钥
                    var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
                    var signingKey = new SymmetricSecurityKey(secretByte);
                    var signingCredentials = new SigningCredentials(signingKey, singingAlorithm);

                    var token = new JwtSecurityToken(
                       issuer: _configuration["Authentication:Issuer"],
                        audience: _configuration["Authentication:audience"],
                        claims,
                        notBefore: DateTime.UtcNow,
                        expires: DateTime.UtcNow.AddDays(1),
                        signingCredentials
                        );
                    var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
                    // return200ok + jwt
                    HttpContext.Response.Cookies.Append("token", "bearer " + tokenStr, new CookieOptions
                    {
                        Expires = DateTime.Now.AddDays(1)
                    });
                    HttpContext.Response.Cookies.Append("userid", Id, new CookieOptions
                    {
                        Expires = DateTime.Now.AddDays(1)
                    });
                    return Json(new { success = true, code = 0, token = "bearer " + tokenStr, userid = Id });
                }
                else
                {
                    return Json(new { success = false, code = -1, msg = "密码错误" });


                }

            }
            else
            {
                return Json(new { success = false, code = -1, msg = "该用户不存在" });


            }



        }
        //[HttpGet]
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}

        // GET api/<AuthorityManagement>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<AuthorityManagement>
        //[HttpPost]
        //public void Post([FromBody] string value)
        //{
        //}

        // PUT api/<AuthorityManagement>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {

        }

        // DELETE api/<AuthorityManagement>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
